<?php

global $mc;
$mc=new Memcache();
$mc->addServer("localhost",11211);

function get_id_by_path($path)
{
	global $mc;
	$pid=$mc->get($path);
	if($pid !== false ) return $pid;
	if($path[0] != "/") return false;
	$list=explode("/",$path);
	$list[0]="/";
	$c=count($list);
	$pid=1;
	for($i=0;$i < $c;$i++)
	{
		if(empty($list[$i])) continue;
		$pid=get_id_by_name_and_pid($list[$i],$pid);
		if(!$pid) return false;
	}
	$mc->set($path,$pid);
	return $pid;
}

function get_list_by_pid($pid)
{
	$p=new_pdo();
	$sql="select * from dir where  pid=:pid";
	$sth=$p->prepare($sql);
	$ret=$sth->execute(array(":pid" => $pid));
	$info=$sth->fetchAll(PDO::FETCH_ASSOC);
	return $info;
}

function new_pdo()
{
	$dsn="mysql:host=192.168.2.5;port=3306;dbname=fuse";
	$p=new PDO($dsn,"fuse","123qwe",array(PDO::ATTR_PERSISTENT => true));
	return $p;
}

function get_id_by_name_and_pid($name,$pid)
{
	$p=new_pdo();
	$sql="select id from dir where name=:name and pid=:pid";
	$sth=$p->prepare($sql);
	$ret=$sth->execute(array(":name" => $name,":pid" => $pid));
	$info=$sth->fetchAll(PDO::FETCH_ASSOC);
	if(count($info) != 1) return false;
	return $info[0]['id'];
}

function listdir($path)
{
	return get_list_by_pid(get_id_by_path($path));
}

function create_nod($pid,$name,$type)
{
	$p=new_pdo();
	$sql="insert ignore into dir(name,type,pid) values (:name,:type,:pid)";
	$sth=$p->prepare($sql);
	$ret=$sth->execute(array(":name" => $name,":type" => $type,":pid" => $pid));
	return $sth->rowCount();
}

function p_create_nod($fullpath,$type)
{
	$dir=dirname($fullpath);
	$pid=get_id_by_path($dir);
	if(!$pid) p_create_nod($dir,1);
	return create_nod($pid,basename($fullpath),$type);
}
/*

$fp=fopen("f.txt","r");
if(!$fp) exit(1);
while(!feof($fp))
{
	$line=trim(fgets($fp));
	if(empty($line)) continue;
	$r=p_create_nod($line,0);
	echo "mknod: ${line} --- $r\n";
}
*/


?>
